<?php

namespace App\Http\Controllers\CallingCards\RMS;

use App\Enums\CallingCards\BaseEnum;
use App\Http\Controllers\BaseController;
use App\Models\Common\ConfigModel;
use App\Models\FeishuCallingCard\FeishuCallingCardPosterBackground;
use App\Service\Common\OssService;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Cache;
use Kuafu\File\FileUtil;

class BackgroundController extends BaseController
{
    public function index(Request $request, $msg = '加载中...')
    {
        $type = $request->get('type', '');
        $backgroundModels = FeishuCallingCardPosterBackground::query()
            ->where('status', FeishuCallingCardPosterBackground::STATUS_ON)
            ->get();
        if ($backgroundModels != null) {
            foreach ($backgroundModels as $backgroundModel){
                if (strtotime($backgroundModel->endDate . '23:59:59') < time()) {
                    $model = FeishuCallingCardPosterBackground::find($backgroundModel->id);
                    $model->status = FeishuCallingCardPosterBackground::STATUS_OFF;
                    $model->save();
                }
            }
        }
        $announcement = '';
        $rule         = '';
        $homeImg      = '';
        $detailImg    = '';
        ConfigModel::query()
            ->where('module', 'callingCards')
            ->get()
            ->each(function ($item) use (&$announcement, &$rule, &$homeImg, &$detailImg){
                if ($item->name == 'announcement') {
                    $announcement = implode("\n", json_decode($item->value, true));
                }
                if ($item->name == 'rule') {
                    $rule = $item->value;
                }
                if ($item->name == 'homeImg') {
                    $homeImg = $item->value;
                }
                if ($item->name == 'detailImg') {
                    $detailImg = $item->value;
                }
            });
        // 获取列表信息...
        $select = FeishuCallingCardPosterBackground::query()
            ->pluck('type')
            ->unique()
            ->filter(function ($item) {
            if ($item === '') {
                return null;
            }
            return $item;
        })->toArray();
        $data = FeishuCallingCardPosterBackground::query()
            ->when(mb_strlen($type), function ($q) use ($type) {
                $q->where('type', $type);
            })
            ->orderBy('status', 'desc')
            ->orderBy('sort', 'desc')
            ->orderBy('id', 'desc')
            ->get();

        return view('calling-cards.rms.background.index')
            ->with('list', $data)
            ->with('msg', $msg)
            ->with('select', $select)
            ->with('announcement', $announcement)
            ->with('rule', $rule)
            ->with('homeImg', $homeImg)
            ->with('detailImg', $detailImg);
    }

    public function save(Request $request)
    {
        ini_set('memory_limit','2048M');
        // 判断客户端IP地址是否为上海办公室的
        $ip = $request->getClientIp();
        if ('prod' == config('app.env')) {
            if ($ip != config('ip.digitalCentre')) {
                //return redirect()->back();
            }
        }
        $file = $request->file('file');
        $sort = (int)$request->post('sort');
        $type = (string)$request->post('type');
        $isInternalUse = (int)$request->post('isInternalUse');
        $startDate = (string)$request->post('startDate');
        $endDate = (string)$request->post('endDate');
        if ($startDate == '') {
            $startDate = date('Y-m-d', time());
        }
        if ($endDate == '') {
            $endDate = date('Y-m-d', strtotime('+7day'));
        }
        if (strtotime($startDate) > strtotime($endDate)) {
            return '时间选择错误';
        }
        if (!$file instanceof UploadedFile) {
            return '没有上传文件';
        }
        $image         = ['png', 'jpeg', 'jpg'];
        $fileExtension = $file->getClientOriginalExtension();
        if (!in_array($fileExtension, $image)) {
            return '非法图片后缀';
        }
        $suffix          = FileUtil::guessSuffix($file->getClientOriginalName());
        try {
            $res = OssService::uploadFile($file->getRealPath(), $suffix);
        }catch (\Exception $exception) {
            return $exception->getMessage();
        }
        if (!strlen($res['path'] ?? '')) {
            return '图片上传到OSS失败';
        }
        $count = FeishuCallingCardPosterBackground::query()
            ->where('imageUrl', $res['path'])
            ->count();
        if ($count) {
            return '图片已存在';
        }
        $model                 = new FeishuCallingCardPosterBackground();
        $model->imageUrl       = $res['path'];
        $model->sort           = $sort;
        $model->type           = $type;
        $model->isInternalUse  = $isInternalUse;
        $model->startDate      = $startDate;
        $model->endDate        = $endDate;
        $model->status         = FeishuCallingCardPosterBackground::STATUS_ON;
        $model->refreshPreview();
        $model->save();
        return redirect()->back();
    }

    public function update(Request $request)
    {
        $backgroundId  = str_replace('"', '', $request->post('backgroundId', 0));
        $sort          = str_replace('"', '', $request->post('sort', -1));
        $type          = str_replace('"', '', $request->post('type', ''));
        $status        = str_replace('"', '', $request->post('status', 0));
        $isInternalUse = str_replace('"', '', $request->post('isInternalUse', 0));
        $startDate     = str_replace('"', '', $request->post('startDate', 0));
        $endDate       = str_replace('"', '', $request->post('endDate', 0));
        $model         = FeishuCallingCardPosterBackground::find($backgroundId);
        if (null === $model) {
            return $this->fail(1,'背景图片不存在');
        }
        if (10 == strlen($startDate)) {
            $model->startDate = $startDate;
        }
        if (10 == strlen($endDate)) {
            $model->endDate = $endDate;
        }
        if ($sort > 0) {
            $model->sort = $sort;
        }
        $model->status = $status;
        $model->type = $type;
        $model->isInternalUse = $isInternalUse;
        $model->save();
        return $this->success();
    }

    public function delete(Request $request)
    {
        $backgroundId  = str_replace('"', '', $request->post('id', 0));
        try {
            FeishuCallingCardPosterBackground::find($backgroundId)->delete();
        } catch (\Exception $exception) {

        }
        return $this->success();
    }

    public function announcementSave(Request $request)
    {
        $announcement = $request->announcement;
        if (mb_strlen($announcement)) {
            $model = ConfigModel::firstOrNew([
                'name' => 'announcement',
                'module' => 'callingCards'
            ]);
            $model->description = '签约奖励公告';
            $model->type = ConfigModel::TYPE_STRING;
            $model->value = json_encode(explode("\n", $announcement), JSON_UNESCAPED_UNICODE);
            $model->save();
        }
        return $this->success();
    }

    public function ruleSave(Request $request)
    {
        $rule = $request->rule;
        if (mb_strlen($rule)) {
            $model = ConfigModel::firstOrNew([
                'name' => 'rule',
                'module' => 'callingCards'
            ]);
            $model->description = '签约规则描述';
            $model->type = ConfigModel::TYPE_STRING;
            $model->value = $rule;
            $model->save();
        }
        return $this->success();
    }

    public function homeImg(Request $request)
    {
        $homeImg = $request->homeImg;
        if (mb_strlen($homeImg)) {
            $model = ConfigModel::firstOrNew([
                'name' => 'homeImg',
                'module' => 'callingCards'
            ]);
            $model->description = '推荐夸父主页图片';
            $model->type = ConfigModel::TYPE_STRING;
            $model->value = $homeImg;
            $model->save();
        }
        return $this->success();
    }

    public function detailImg(Request $request)
    {
        $detailImg = $request->detailImg;
        if (mb_strlen($detailImg)) {
            $model = ConfigModel::firstOrNew([
                'name' => 'detailImg',
                'module' => 'callingCards'
            ]);
            $model->description = '推荐夸父详情页图片';
            $model->type = ConfigModel::TYPE_STRING;
            $model->value = $detailImg;
            $model->save();
        }
        return $this->success();
    }

}
